# -*- coding: utf-8 -*-
"""
主窗口模块
"""

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                            QHBoxLayout, QPushButton, QTableWidget, QTableWidgetItem,
                            QTabWidget, QMenuBar, QStatusBar, QMessageBox, QSplitter,
                            QTreeWidget, QTreeWidgetItem, QLabel, QFrame)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QIcon, QFont

from config import APP_NAME, APP_VERSION
from styles import GLOBAL_STYLESHEET
from modules.ip_management import IPManagementWidget
from modules.asset_management import AssetManagementWidget
from modules.middleware_management import MiddlewareManagementWidget
from modules.app_system_management import AppSystemManagementWidget
from modules.os_account_management import OSAccountManagementWidget
from modules.system_settings import SystemSettingsWidget
from modules.backup_dialog import BackupDialog

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle(f"{APP_NAME} v{APP_VERSION}")
        self.setGeometry(100, 100, 1400, 900)
        self.setMinimumSize(1200, 800)
        
        # 设置应用图标（如果有的话）
        # self.setWindowIcon(QIcon('icon.png'))
        
        self.init_ui()
        self.init_menu()
        self.init_status_bar()
        
        # 设置全局样式
        self.setStyleSheet(GLOBAL_STYLESHEET)
    
    def init_ui(self):
        """初始化用户界面"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)
        main_layout.addWidget(splitter)
        
        # 左侧导航树
        self.nav_tree = QTreeWidget()
        self.nav_tree.setHeaderLabel("功能模块")
        self.nav_tree.setMaximumWidth(200)
        self.nav_tree.itemClicked.connect(self.on_nav_item_clicked)
        
        # 添加导航项
        self.setup_navigation()
        splitter.addWidget(self.nav_tree)
        
        # 右侧内容区域
        self.content_stack = QTabWidget()
        self.content_stack.setTabsClosable(True)
        self.content_stack.tabCloseRequested.connect(self.close_tab)
        splitter.addWidget(self.content_stack)
        
        # 设置分割器比例
        splitter.setSizes([200, 1000])
        
        # 默认显示IP管理页面
        self.open_ip_management()
    
    def setup_navigation(self):
        """设置导航树"""
        # 设置导航树样式
        self.nav_tree.setIndentation(15)
        self.nav_tree.setRootIsDecorated(True)
        self.nav_tree.setAlternatingRowColors(True)
        
        # 基础信息管理
        basic_info = QTreeWidgetItem(self.nav_tree, ["📊 基础信息管理"])
        basic_info.setExpanded(True)
        basic_info.setFont(0, QFont("Microsoft YaHei", 10, QFont.Bold))
        
        ip_item = QTreeWidgetItem(basic_info, ["🌐 IP地址管理"])
        ip_item.setData(0, Qt.UserRole, "ip_management")
        
        asset_item = QTreeWidgetItem(basic_info, ["🖥️ 资产信息管理"])
        asset_item.setData(0, Qt.UserRole, "asset_management")
        
        # 系统管理
        system_mgmt = QTreeWidgetItem(self.nav_tree, ["⚙️ 系统管理"])
        system_mgmt.setExpanded(True)
        system_mgmt.setFont(0, QFont("Microsoft YaHei", 10, QFont.Bold))
        
        middleware_item = QTreeWidgetItem(system_mgmt, ["🔧 中间件管理"])
        middleware_item.setData(0, Qt.UserRole, "middleware_management")
        
        app_system_item = QTreeWidgetItem(system_mgmt, ["📱 应用系统管理"])
        app_system_item.setData(0, Qt.UserRole, "app_system_management")
        
        os_account_item = QTreeWidgetItem(system_mgmt, ["👤 系统账号管理"])
        os_account_item.setData(0, Qt.UserRole, "os_account_management")
        
        # 系统设置
        system_settings = QTreeWidgetItem(self.nav_tree, ["🛠️ 系统设置"])
        system_settings.setExpanded(True)
        system_settings.setFont(0, QFont("Microsoft YaHei", 10, QFont.Bold))
        
        settings_item = QTreeWidgetItem(system_settings, ["⚙️ 系统设置"])
        settings_item.setData(0, Qt.UserRole, "system_settings")
        
        backup_item = QTreeWidgetItem(system_settings, ["💾 数据备份"])
        backup_item.setData(0, Qt.UserRole, "backup")
    
    def on_nav_item_clicked(self, item, column):
        """导航项点击事件"""
        module_type = item.data(0, Qt.UserRole)
        if not module_type:
            return
        
        if module_type == "ip_management":
            self.open_ip_management()
        elif module_type == "asset_management":
            self.open_asset_management()
        elif module_type == "middleware_management":
            self.open_middleware_management()
        elif module_type == "app_system_management":
            self.open_app_system_management()
        elif module_type == "os_account_management":
            self.open_os_account_management()
        elif module_type == "system_settings":
            self.open_system_settings()
        elif module_type == "backup":
            self.open_backup_dialog()
    
    def open_ip_management(self):
        """打开IP管理页面"""
        widget = IPManagementWidget()
        self.add_tab("IP地址管理", widget)
    
    def open_asset_management(self):
        """打开资产管理页面"""
        widget = AssetManagementWidget()
        self.add_tab("资产信息管理", widget)
    
    def open_middleware_management(self):
        """打开中间件管理页面"""
        widget = MiddlewareManagementWidget()
        self.add_tab("中间件管理", widget)
    
    def open_app_system_management(self):
        """打开应用系统管理页面"""
        widget = AppSystemManagementWidget()
        self.add_tab("应用系统管理", widget)
    
    def open_os_account_management(self):
        """打开系统账号管理页面"""
        widget = OSAccountManagementWidget()
        self.add_tab("系统账号管理", widget)
    
    def open_system_settings(self):
        """打开系统设置页面"""
        widget = SystemSettingsWidget()
        self.add_tab("系统设置", widget)
    
    def open_backup_dialog(self):
        """打开备份对话框"""
        dialog = BackupDialog(self)
        dialog.exec_()
    
    def add_tab(self, title, widget):
        """添加标签页"""
        # 检查是否已经存在相同的标签页
        for i in range(self.content_stack.count()):
            if self.content_stack.tabText(i) == title:
                self.content_stack.setCurrentIndex(i)
                return
        
        # 添加新标签页
        index = self.content_stack.addTab(widget, title)
        self.content_stack.setCurrentIndex(index)
    
    def close_tab(self, index):
        """关闭标签页"""
        if self.content_stack.count() > 1:
            self.content_stack.removeTab(index)
        else:
            QMessageBox.information(self, "提示", "至少需要保留一个标签页")
    
    def init_menu(self):
        """初始化菜单栏"""
        menubar = self.menuBar()
        menubar.setStyleSheet("font-size: 14px;")
        
        # 文件菜单
        file_menu = menubar.addMenu('📁 文件')
        
        # 导入菜单
        import_menu = file_menu.addMenu('📥 导入')
        
        import_ip_action = import_menu.addAction('🌐 导入IP数据')
        import_ip_action.triggered.connect(self.import_ip_data)
        
        import_asset_action = import_menu.addAction('🖥️ 导入资产数据')
        import_asset_action.triggered.connect(self.import_asset_data)
        
        # 导出菜单
        export_menu = file_menu.addMenu('📤 导出')
        
        export_ip_action = export_menu.addAction('🌐 导出IP数据')
        export_ip_action.triggered.connect(self.export_ip_data)
        
        export_app_action = export_menu.addAction('📱 导出应用系统数据')
        export_app_action.triggered.connect(self.export_app_system_data)
        
        export_account_action = export_menu.addAction('👤 导出系统账号数据')
        export_account_action.triggered.connect(self.export_os_account_data)
        
        file_menu.addSeparator()
        
        # 退出
        exit_action = file_menu.addAction('🚪 退出')
        exit_action.triggered.connect(self.close)
        
        # 工具菜单
        tools_menu = menubar.addMenu('🔧 工具')
        
        backup_action = tools_menu.addAction('💾 数据备份')
        backup_action.triggered.connect(self.open_backup_dialog)
        
        template_action = tools_menu.addAction('📋 下载Excel模板')
        template_action.triggered.connect(self.download_templates)
        
        # 帮助菜单
        help_menu = menubar.addMenu('❓ 帮助')
        
        about_action = help_menu.addAction('ℹ️ 关于')
        about_action.triggered.connect(self.show_about)
    
    def init_status_bar(self):
        """初始化状态栏"""
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 添加状态信息
        self.status_label = QLabel("🟢 系统就绪")
        self.status_label.setStyleSheet("color: #28a745; font-weight: 500; padding: 2px 8px;")
        self.status_bar.addWidget(self.status_label)
        
        # 添加用户信息
        self.user_label = QLabel("👤 管理员")
        self.user_label.setStyleSheet("color: #6c757d; padding: 2px 8px;")
        self.status_bar.addWidget(self.user_label)
        
        # 添加数据库状态
        self.db_label = QLabel("🗄️ 数据库已连接")
        self.db_label.setStyleSheet("color: #17a2b8; padding: 2px 8px;")
        self.status_bar.addWidget(self.db_label)
        
        # 添加分隔符
        separator = QLabel("|")
        separator.setStyleSheet("color: #dee2e6; margin: 0 10px;")
        self.status_bar.addWidget(separator)
        
        # 添加时间显示
        self.time_label = QLabel()
        self.time_label.setStyleSheet("color: #6c757d; font-weight: 500; padding: 2px 8px;")
        self.status_bar.addPermanentWidget(self.time_label)
        
        # 定时更新时间
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)
        self.update_time()
    
    def update_time(self):
        """更新时间显示"""
        from datetime import datetime
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.time_label.setText(current_time)
    
    def set_style(self):
        """设置应用样式"""
        style = """
        /* 主窗口样式 */
        QMainWindow {
            background-color: #f8f9fa;
            color: #333;
        }
        
        /* 导航树样式 */
        QTreeWidget {
            background-color: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 8px;
            font-size: 14px;
        }
        
        QTreeWidget::item {
            padding: 8px 4px;
            border-bottom: 1px solid #f8f9fa;
            margin: 2px 0;
            border-radius: 4px;
        }
        
        QTreeWidget::item:selected {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1, 
                                       stop:0 #4a90e2, stop:1 #357abd);
            color: white;
            font-weight: 500;
        }
        
        QTreeWidget::item:hover {
            background-color: #f1f3f4;
        }
        
        QTreeWidget::item:selected:hover {
            background: qlineargradient(x1:0, y1:0, x2:0, y2:1, 
                                       stop:0 #5ba0f2, stop:1 #4580cd);
        }
        
        /* 标签页样式 */
        QTabWidget::pane {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            background-color: #ffffff;
            top: -2px;
        }
        
        QTabBar::tab {
            background-color: #f8f9fa;
            padding: 10px 20px;
            margin-right: 4px;
            border-top-left-radius: 8px;
            border-top-right-radius: 8px;
            font-weight: 500;
            font-size: 14px;
            color: #666;
        }
        
        QTabBar::tab:selected {
            background-color: #ffffff;
            color: #4a90e2;
            border-bottom: 3px solid #4a90e2;
        }
        
        QTabBar::tab:hover {
            background-color: #e9ecef;
        }
        
        QTabBar::tab:selected:hover {
            background-color: #ffffff;
        }
        
        /* 菜单栏样式 */
        QMenuBar {
            background-color: #ffffff;
            border-bottom: 1px solid #e9ecef;
            padding: 2px;
        }
        
        QMenuBar::item {
            padding: 10px 16px;
            font-size: 14px;
            border-radius: 4px;
        }
        
        QMenuBar::item:selected {
            background-color: #f1f3f4;
            color: #4a90e2;
        }
        
        QMenu {
            background-color: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 4px;
        }
        
        QMenu::item {
            padding: 8px 16px;
            border-radius: 4px;
        }
        
        QMenu::item:selected {
            background-color: #f1f3f4;
            color: #4a90e2;
        }
        
        /* 状态栏样式 */
        QStatusBar {
            background-color: #ffffff;
            border-top: 1px solid #e9ecef;
            color: #666;
            font-size: 12px;
        }
        
        /* 按钮样式 */
        QPushButton {
            background-color: #4a90e2;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 8px 16px;
            font-size: 14px;
            font-weight: 500;
        }
        
        QPushButton:hover {
            background-color: #357abd;
        }
        
        QPushButton:pressed {
            background-color: #2968aa;
        }
        
        QPushButton:disabled {
            background-color: #e9ecef;
            color: #adb5bd;
        }
        
        /* 输入框样式 */
        QLineEdit, QComboBox {
            border: 1px solid #ced4da;
            border-radius: 6px;
            padding: 8px 12px;
            font-size: 14px;
            background-color: #ffffff;
        }
        
        QLineEdit:focus, QComboBox:focus {
            border: 2px solid #4a90e2;
            outline: none;
        }
        
        /* 表格样式 */
        QTableWidget {
            background-color: #ffffff;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            gridline-color: #f1f3f4;
            font-size: 13px;
        }
        
        QTableWidget::item {
            padding: 8px;
            border-bottom: 1px solid #f1f3f4;
        }
        
        QTableWidget::item:selected {
            background-color: #e3f2fd;
            color: #1976d2;
        }
        
        QHeaderView::section {
            background-color: #f8f9fa;
            padding: 10px 8px;
            border: none;
            border-right: 1px solid #e9ecef;
            border-bottom: 2px solid #e9ecef;
            font-weight: 600;
            font-size: 13px;
        }
        
        QHeaderView::section:first {
            border-top-left-radius: 8px;
        }
        
        QHeaderView::section:last {
            border-right: none;
            border-top-right-radius: 8px;
        }
        
        /* 分组框样式 */
        QGroupBox {
            font-weight: 600;
            font-size: 14px;
            color: #333;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            margin-top: 10px;
            padding-top: 10px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 10px;
            padding: 0 5px 0 5px;
        }
        
        /* 标签样式 */
        QLabel {
            color: #495057;
            font-size: 14px;
        }
        
        /* 分割器样式 */
        QSplitter::handle {
            background-color: #e9ecef;
            width: 2px;
        }
        
        QSplitter::handle:hover {
            background-color: #adb5bd;
        }
        """
        self.setStyleSheet(style)
    
    def import_ip_data(self):
        """导入IP数据"""
        from PyQt5.QtWidgets import QFileDialog
        from excel_handler import ExcelHandler
        
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择IP数据文件", "", "Excel文件 (*.xlsx *.xls)"
        )
        
        if file_path:
            try:
                handler = ExcelHandler()
                success_count, error_messages = handler.import_ip_data(file_path)
                
                message = f"成功导入 {success_count} 条记录"
                if error_messages:
                    message += f"\n失败 {len(error_messages)} 条记录"
                    message += "\n错误详情：\n" + "\n".join(error_messages[:10])
                    if len(error_messages) > 10:
                        message += f"\n...还有 {len(error_messages) - 10} 条错误"
                
                QMessageBox.information(self, "导入结果", message)
                
                # 刷新IP管理页面
                for i in range(self.content_stack.count()):
                    if self.content_stack.tabText(i) == "IP地址管理":
                        widget = self.content_stack.widget(i)
                        widget.load_data()
                        break
                        
            except Exception as e:
                QMessageBox.critical(self, "错误", f"导入失败：{str(e)}")
    
    def export_ip_data(self):
        """导出IP数据"""
        try:
            from excel_handler import ExcelHandler
            
            handler = ExcelHandler()
            file_path = handler.export_ip_data()
            
            QMessageBox.information(self, "导出成功", f"IP数据已导出到：\n{file_path}")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出失败：{str(e)}")
    
    def export_app_system_data(self):
        """导出应用系统数据"""
        try:
            from excel_handler import ExcelHandler
            
            handler = ExcelHandler()
            file_path = handler.export_app_system_data()
            
            QMessageBox.information(self, "导出成功", f"应用系统数据已导出到：\n{file_path}")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出失败：{str(e)}")
    
    def export_os_account_data(self):
        """导出系统账号数据"""
        try:
            from excel_handler import ExcelHandler
            
            handler = ExcelHandler()
            file_path = handler.export_os_account_data()
            
            QMessageBox.information(self, "导出成功", f"系统账号数据已导出到：\n{file_path}")
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出失败：{str(e)}")
    
    def download_templates(self):
        """下载Excel模板"""
        try:
            from excel_handler import ExcelHandler
            
            handler = ExcelHandler()
            
            # 创建所有模板
            templates = [
                ("IP管理模板", handler.create_ip_template()),
                ("资产信息模板", handler.create_asset_template()),
                ("中间件模板", handler.create_middleware_template()),
                ("应用系统模板", handler.create_app_system_template()),
                ("系统账号模板", handler.create_os_account_template())
            ]
            
            message = "模板已生成到exports目录：\n"
            for name, path in templates:
                message += f"• {name}: {path}\n"
            
            QMessageBox.information(self, "模板下载", message)
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"模板生成失败：{str(e)}")
    
    def import_asset_data(self):
        """导入资产数据"""
        QMessageBox.information(self, "提示", "资产数据导入功能正在开发中")
    
    def show_about(self):
        """显示关于对话框"""
        QMessageBox.about(self, "关于", 
                         f"{APP_NAME} v{APP_VERSION}\n\n"
                         "开发者：谢囧囧\n"
                         "邮箱：viitii@qq.com\n\n"
                         "这是一个本地化部署的信息台账管理系统，\n"
                         "用于统一管理IP地址、资产信息、中间件、\n"
                         "应用系统和系统账号等信息。")

def main():
    app = QApplication(sys.argv)
    
    # 设置应用程序属性
    app.setApplicationName(APP_NAME)
    app.setApplicationVersion(APP_VERSION)
    
    # 创建主窗口
    window = MainWindow()
    window.show()
    
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()